/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package com.moon.admin.sys.controller;

import java.util.List;

import com.moon.admin.sys.cache.ConfigCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.moon.admin.framework.domain.MoonTree;
import com.moon.admin.framework.secure.annotation.FormRepeat;
import com.moon.admin.framework.secure.annotation.PreAuth;
import com.moon.admin.framework.springmvc.domain.R;
import com.moon.admin.framework.syslog.annotation.SysLog;
import com.moon.admin.framework.util.ToolUtils;
import com.moon.admin.sys.entity.SysDeptEntity;
import com.moon.admin.sys.service.SysDeptService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 部门
 * @author ninglong
 */
@RestController
@RequestMapping(value="/dept/sysDept")
@Api(value = "部门管理",tags = "部门管理")
public class SysDeptController {

	@Autowired
	private SysDeptService deptService;

    /**
     * 加载组织架构列表树
     */
    @GetMapping("/list")
    public R<List<SysDeptEntity>> list(){
    	List<SysDeptEntity> tree = deptService.getDeptList();
        return R.success(tree);
    }
    
	/**
	 * 获取所有部门及岗位,以树型结构展示
	 */
	@GetMapping("getDeptAndPostTreeList")
	public R<List<MoonTree>> getDeptAndPostTreeList(){
		return R.success(deptService.getDeptTreeList(true));
	}
	
	/**
	 * 获取所有部门,以树型结构展示
	 */
	@GetMapping("getDeptTreeList")
	public R<List<MoonTree>> getDeptTreeList(){
		return R.success(deptService.getDeptTreeList(false));
	}
    
    /**
     * 保存部门
     */
    @PostMapping("/save")
    @ApiOperation(value="保存部门")
    @SysLog(mod="部门管理",fun="保存部门")
    @PreAuth(value={"sys_dept_edit","sys_dept_add"})
    @FormRepeat
    public R<Void> save(@RequestBody SysDeptEntity deptEntity){
    	if(deptEntity.getId()!=null) {
			ConfigCache.cleanCache();
    	}
    	boolean  bool= deptService.saveOrUpdate(deptEntity);
        return bool?R.success():R.fail("操作成功");
    }
	
	@GetMapping(value = "removeById")
	@PreAuth("sys_dept_remove")
	@SysLog(fun="部门管理",mod="删除部门")
	@FormRepeat
	public R<Void> removeById(Integer id) {
		if(ToolUtils.isNull(id)) {
			return R.fail("请选择要删除的部门");
		}
		//需要判断是否有下级部门
		int count = deptService.count(Wrappers.<SysDeptEntity>lambdaQuery().eq(SysDeptEntity::getParentId, id));
		if(count>0) {
			return R.fail("当前部门还有下属部门，不能删除");
		}
		ConfigCache.cleanCache();
		return R.status(deptService.removeById(id));
	}

	@GetMapping("/cleanCache")
	@ApiIgnore
	public R<Void> cleanCache(){
		ConfigCache.cleanCache();
		return R.success();
	}
}